<?php

namespace app\admin\controller\zbtask;

use app\admin\logic\DelLogic;
use app\admin\logic\MoneyLogic;
use app\admin\logic\statistics\MoneyStatistics;
use app\admin\logic\Transfer;
use app\admin\model\dealer\DealerCompany;
use app\admin\model\Statistics;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\library\task\ImportService;
use app\common\library\task\RateService;
use app\common\utils\Utils;
use think\Db;
use app\common\validate\zbtask\Money as MoneyValidate;
use think\exception\ValidateException;
use app\common\model\zbtask\Zbtask as TaskModel;

/**
 * 众包费
 *
 * @icon fa fa-circle-o
 */
class Money extends Backend
{

    //做了数据限制
    protected $dataLimit = 'auth';
    protected $dataLimitField = 'company_id';
    protected $dataLimitFieldAutoFill = false;

    /**
     * 获取数据限制的管理员ID
     * 禁用数据限制时返回的是null
     * @return mixed
     */
    protected function getDataLimitAdminIds()
    {
        if (!$this->dataLimit) {
            return null;
        }
        //超级管理员
        if ($this->auth->isSuperAdmin() || TYPE == 0) {
            return null;
        }
        if (TYPE == 1) {
            return [TYPE_ID];
        }else if (TYPE == 2) {
            $company_ids = [];
            if (in_array($this->dataLimit, ['auth', 'personal'])) {
                $where['dealer_id'] = TYPE_ID;
                $company_ids = DealerCompany::where($where)->column('company_id');
            }
            if (!$company_ids) {
                $this->error('参数错误');
            }
            return $company_ids;
        }

    }
    /**
     * Money模型对象
     * @var \app\common\model\zbtask\Money
     */
    protected $model = null;
    protected $searchFields = 'id,user.real_name,user.identity_card,zbtask.name';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\zbtask\Money;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("transferTypeList", $this->model->getTransferTypeList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user','zbtask'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user','zbtask'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','user_id','colorbg','company_id','month','year','json_rate','order_id','task_id','money','ca_tax','ca_money','get_money','item','tax_money','already_money','createtime','status','type','transfer_type','pay_time','bank_card','pay_type']);
                $row->visible(['user']);
				$row->getRelation('user')->visible(['id','real_name', 'identity_card']);
				$row->visible(['zbtask']);
				$row->getRelation('zbtask')->visible(['id','name']);
                $row->month = MoneyLogic::instance()->getMoneyByUserId($row['user']['id'], 'month', $row['createtime']);
                $row->year = MoneyLogic::instance()->getMoneyByUserId($row['user']['id'], 'year', $row['createtime']);

                $row->colorbg = '';
                if ($row->month >= config('site.month_limit')) {
                    $row->colorbg = 'warning';
                }
                if ($row->year >= config('site.year_limit')) {
                    $row->colorbg = 'danger';
                }
				$row->json_rate = json_decode($row->json_rate, true);
				//当前所处于的段位 以及是否跨党
            }
            $list = collection($list)->toArray();

            $statistics = MoneyStatistics::instance()->setWhere($where)->getRes();
            $str = MoneyStatistics::toDefaultString($statistics);
            $result = array("total" => $total, "rows" => $list, 'statistics' => $str);
            return json($result);
        }
        return $this->view->fetch();
    }
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $user = User::get($row['user_id']);
        $task = TaskModel::get($row['task_id']);
        $row['real_name'] = $user['real_name'];
        $row['task_name'] = $task['name'];
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            //如果已经打款成功 就不能在对数据进行更改
            if ($row['transfer_type'] == 2) {
                $this->error('该众包费已经打款成功，不能在进行修改');
            }
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row['json_rate'] = json_decode($row['json_rate'], true);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function reImport() {
        $ids = input('ids/d', 0);
        $money_type = input('money_type/d', 0);
        $money = input('money', 0);
        $moneyModel = \app\common\model\zbtask\Money::get($ids);
        if (!$moneyModel) {
            $this->error('参数错误');
        }

        if ($moneyModel['transfer_type'] == 1 || $moneyModel['transfer_type'] == 2) {
            $this->error('打款中和打款成功不能重新计算');
        }
        if (!in_array($money_type, [1, 2])) {
            $this->error('金额类别填写错误');
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($moneyModel[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $moneyModel->money = $money;
        $moneyModel->money_type = $money_type;
        Db::startTrans();
        try {
            //重构税率 排除要删除的数据
            ImportService::instance()->reRate($moneyModel, $ids)->selectAllNeedChange($moneyModel); //对本条数据进行解析
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('重新计算成功');
    }
    /*
   * 打款日志
   * ids          //众包费ids
   * */
    public function transferLog() {
        $ids = input('ids/d', 0);
        if (!$ids) {
            $this->error('众包费ID传递错误');
        }
        $list = Db::name('zbtask_moneylog')->order('createtime desc')->where('task_money_id', $ids)->select();

        $this->assign('list', $list);

        return $this->view->fetch();
    }

    /**
     * 确认提交正确数据
     */
    public function check() {
        $this->relationSearch = true;
        $postData = $this->request->post();
        $ids = $postData['ids'];
        $pay_type = $postData['pay_type'];  //拒绝
        $remark = $postData['remark'];      //备注
        if (!$pay_type || !in_array($pay_type, [1, 2])) {
            $this->error('参数错误');
        }
        $where = [];
        if ($ids == 'all') {
            $this->request->get(['filter' => $postData['filter'], 'op' => $postData['op'], 'search'=> $postData['search']]);
            list($where) = $this->sureParams();
        } else {
            $where['money.id'] = ['in', $ids];
        }
        Db::startTrans();
        try {
            //审核驳回会导致税率重新计算
            $res = $this->model->with(['user','zbtask'])->where($where)->setField(['money.type'=> $pay_type, 'money.remark' => $remark]);

            //审核驳回重新计算税率
            if ($pay_type == 2) {
                $list = $this->model->with(['user','zbtask'])->where($where)->select();
                $ids = $this->model->with(['user','zbtask'])->where($where)->column('money.id');
                if (count($ids) > 500) {
                    $this->error('一次审核不能超过500条数据');
                }
                //审核驳回把税率 置为无效
                Db::name('zbtask_money_rate')->where(['task_money_id'=> ['in', $ids]])->setField(['status' => 1]);
                //当前数据  启上数据，排除要驳回的所有数据
                foreach ($list as $k => $v) {
                    ImportService::instance()->selectAllNeedChange($v, ['id'=> ['not in', $ids]], $ids); //对本条数据进行解析
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('审核成功');
    }


    public function transpage() {
        $search = $this->request->param();
        $select = $search['select'];     //当前选择
        $current = $search['curPage'];   //当前页面
        $task_id = $search['task_id'];
        if ($this->request->isAjax()) {
            $this->transfer();
        }
        //当前任务
        $select_sum = MoneyStatistics::instance()->setWhere(['money.id' => ['in', $select]])->getRes();
        $select_sum = MoneyStatistics::toDefaultString($select_sum);
        $current_sum = MoneyStatistics::instance()->setWhere(['money.id' => ['in', $current]])->getRes();
        $current_sum = MoneyStatistics::toDefaultString($current_sum);
        if ($task_id) {
            $task_sum = MoneyStatistics::instance()->setWhere(['money.task_id' => $task_id])->getRes();
            $task_sum = MoneyStatistics::toDefaultString($task_sum);
        } else {
            $task_sum = false;
        }

        $this->assign([
            'select' => $select,
            'current' => $current,
            'task_id' => $task_id,
            'select_sum' => $select_sum,
            'current_sum' => $current_sum,
            'task_sum' => $task_sum,
        ]);
        return $this->view->fetch();
    }
    /**
     * 打款
     */
    private function transfer() {
        $data = $this->request->param();
        $target = $data['target'];
        $transferType = $data['transfer_type'];
        $pay_type = $data['pay_type'];
        $remark = $data['remark'];
        $task_id = $data['task_id'];

        if ($target === 'all') {
            if (!$task_id) {
                $this->error('参数错误');
            }
            $where['task_id'] = $task_id;
        } else {
            $where['id'] = ['in', $target];
        }
        try {
            Db::startTrans();
            Transfer::instance()->setPayType($pay_type, $transferType)
                ->setWhere($where)->setUpdate(['remark'=>$remark])->getList()->toTransfer();
            Db::commit();
        }  catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('打款已提交，正在打款');
    }
   protected function sureParams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        //批量导入 必须在某一个任务下面进行
        if (!isset($filter['task_id']) || !$filter['task_id']) {
            $this->error('全部审核的情况下，必须首先选择一个任务');
        }
        $where = [];
        $tableName = '';
        if ($relationSearch) {
            if (!empty($this->model)) {
                $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
                $name = $this->model->getTable();
                $tableName = $name . '.';
            }
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$tableName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET('{$v}', " . ($relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }

        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where];
    }



    /**经销商众包费流水*/
    public function dealermoney(){
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $ids = $this->request->request('ids');  //经销商id
        $this->assignconfig('dealer_id', $ids);
        if (!$ids) {
            if(TYPE == 2){
                $ids = TYPE_ID;
            }else{
                $this->error('经销商信息有误');
            }
        }
        $statisticsModel = model('statistics');
        //总应发
        $dealermoney = $statisticsModel->dealerAmount($ids);
        //总佣金
        $dealermoneyamount = MoneyStatistics::instance()->setWhere(array('dealer_com.dealer_id'=>$ids))->getDealerMoney();
        //众包费总笔数
        $zbtask_money_count = $statisticsModel->zbtaskMoneyCount($ids, 2);
        //总推广
        $dealer_company_count = $statisticsModel->dealerCompanyCount($ids);
        //累计提现
        $dealer_withdraw_amount = model('admin/dealer/MoneyLog')->getWithdrawAmount($ids);
        //经销商余额
        $dealer_usermoney = model('admin/dealer/Dealer')->where(array('id'=>$ids))->value('usermoney');

        $this->assign('dealermoney', $dealermoney);
        $this->assign('dealermoneyamount', $dealermoneyamount);
        $this->assign('zbtask_money_count', $zbtask_money_count);
        $this->assign('dealer_company_count', $dealer_company_count);
        $this->assign('dealer_withdraw_amount', $dealer_withdraw_amount);
        $this->assign('dealer_usermoney', $dealer_usermoney);

        if ($this->request->isAjax())
        {
            $filter = $this->request->get("filter", '');
            $op = $this->request->get("op", '', 'trim');
            $filter = (array)json_decode($filter, true);
            $op = (array)json_decode($op, true);
            $company_ids = [];
            if (isset($filter['company_id'])) {
                array_push($company_ids, $filter['company_id']);
                unset($filter['company_id']);
            }

            //经销商-》比例  -》company_id
            //经销商企业，费率数据
            $company_ids_rate = DealerCompany::where(array('dealer_id'=>$ids))
                ->column('rate', 'company_id');
            $key_ids = array_keys($company_ids_rate);
            $company_ids = array_merge($company_ids, $key_ids);
            if ($company_ids) {
                $filter['company_id'] = $company_ids;
                $op['company_id'] = 'in';
                $this->request->get(['filter' => json_encode($filter), 'op' => json_encode($op)]);
            }
            if (!$company_ids) {
                $result = array("total" => 0, "rows" => [], 'statistics' => '无数据');
                return json($result);
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['user','zbtask', 'company'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['user','zbtask', 'company'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible(['id','user_id','order_id','task_id','money','ca_tax','ca_money','get_money','item','tax_money','already_money','createtime',
                    'status','type','transfer_type','pay_time','bank_card','pay_type','company_id']);
                $row->visible(['user']);
                $row->getRelation('user')->visible(['id','real_name', 'identity_card']);
                $row->visible(['zbtask']);
                $row->getRelation('zbtask')->visible(['id','name']);
                $row->visible(['company']);
                $row->getRelation('company')->visible(['id','name']);
            }
            $list = collection($list)->toArray();
            foreach($list as $key => $value){
                  $list[$key]['dealer_money'] = round(Utils::processMoney($value['money'], $company_ids_rate[$value['company_id']], '*', 5), 2);
            }

            $statistics = MoneyStatistics::instance()->setWhere($where)->getRes();
            $str = MoneyStatistics::toDefaultString($statistics);
            $dealer_money_amount = MoneyStatistics::instance()->setWhere($where)->getDealerMoney();
            $str .= ' , 总佣金：'.$dealer_money_amount;
            $result = array("total" => $total, "rows" => $list, 'statistics' => $str);

            return json($result);
        }
        return $this->view->fetch();
    }



    /**
     * 删除
     */
    public function del($ids = "")
    {

        if ($ids) {
            //开启了数据限制 只能删除和查询自己的 如果是管理员 都可以删除
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where('id', 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    DelLogic::instance()->taskMoney($v['id']);  //删除逻辑
                    $count += $v->delete();
                    //重构税率 排除要删除的数据
                    ImportService::instance()->delReRate($v);
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
